package io.mft.as.ar.gateway.pool.client;

import com.thinkive.tbascli.TBASClient;

import cn.hutool.core.util.ObjectUtil;
import io.mft.as.ar.gateway.pool.BusPool;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PoolAsClientV2 extends TBASClient implements PoolAsClient
{
    
    private boolean       isUsable = true;
    
    private BusPool       quote;
    
    private Long          timestamp;
    
    public void freshTime()
    {
        this.timestamp = System.currentTimeMillis();
    }
    
    public Long getTime()
    {
        if ( null == this.timestamp )
        {
            this.timestamp = System.currentTimeMillis();
        }
        return this.timestamp;
    }
    
    @Override
    public void setIsUsable(boolean isUsable)
    {
        this.isUsable = isUsable;
    }
    
    public PoolAsClientV2(String host, int port, int recvTimeout, String encryptKey, BusPool pool)
    {
        super();
        super.setConnect(host, port);
        super.connect();
        this.quote = pool;
        if ( recvTimeout > 0 )
        {
            super.setRecvTimeout(recvTimeout);
        }
        if ( ObjectUtil.isNotEmpty(encryptKey) )
        {
            super.setKey(encryptKey);
        }
        this.freshTime();
    }
    
    /* (non-Javadoc)
     * @see com.thinkive.gateway.v2.pool.client.PoolAsClient#close()
     */
    @Override
    public void close()
    {
        this.freshTime();
        if ( isUsable && quote.getQueueSize() < quote.getPoolSize() )
        {
            quote.offer(this); 
        }
        else
        {
            try
            {
                super.disConnect();
                super.close();
            }
            catch (Exception ex)
            {
                log.error("", ex);
            }
        }
    }
}
